﻿using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace SuperSocketServer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Run(() =>
            {
                AppServer appServer = new AppServer();
                appServer.NewSessionConnected += appServer_NewSessionConnected;
                appServer.NewRequestReceived += appServer_NewRequestReceived;
                appServer.SessionClosed += appServer_SessionClosed;

                ServerConfig serverConfig = new ServerConfig()
                {
                    Ip = "127.0.0.1",
                    Port = 9514,
                    TextEncoding = "UTF-8",
                    Mode = SocketMode.Tcp,
                };

                if (!appServer.Setup(serverConfig))
                {
                    return;
                }
                if (!appServer.Start())
                {
                    return;
                }
            });
        }
        private void appServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
        {
            try
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    txbMsg.Text += requestInfo.Key;
                });                
            }
            catch (Exception ex)
            {
                log4net.LogManager.GetLogger("TCP").Warn("接受数据失败", ex);
            }
        }

        static void appServer_NewSessionConnected(AppSession session)
        {

        }

        static void appServer_SessionClosed(AppSession session, CloseReason reason)
        {
            log4net.LogManager.GetLogger("TCP").Warn("TCP客户端断连，原因：" + reason.ToString());
        }
    }
}
